<template>
  <div>
    <div class="handel-header">
      <el-popover v-model="showPopover" placement="bottom" width="700" style="padding: 0 !important" trigger="click">
        <crm-relative ref="crmrelative" crm-type="product" v-if="showSelectView" radio @close="showPopover = false"
          @changeCheckout="selectInfos" />
        <el-button slot="reference" v-show="productList.length == 0" type="primary" @click="showSelectView = true">
          添加产品
        </el-button>
      </el-popover>
    </div>
    <el-table :data="productList" style="width: 620px">
      <el-table-column prop="name" label="产品名称" />
      <el-table-column prop="category_id_info" label="产品类别" />
      <el-table-column prop="unit" label="单位" />
      <el-table-column prop="price" label="标准价格" />
      <el-table-column label="售价">
        <template slot-scope="scope">
          <el-input v-model="scope.row.sales_price" @input="salesPriceChange(scope)"
            @blur="scope.row.sales_price || (scope.row.sales_price = 0)" placeholder="请输入" />
        </template>
      </el-table-column>
      <el-table-column label="数量">
        <template slot-scope="scope">
          <el-input v-model="scope.row.num" @input="numChange(scope)" @blur="scope.row.num || (scope.row.num = 0)"
            placeholder="请输入" />
        </template>
      </el-table-column>
      <el-table-column label="折扣（%）">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.discount" :controls="false" :min="0" :max="100" @change="discountChange(scope)"
            @blur="scope.row.discount || (scope.row.discount = 0)" placeholder="请输入" style="width: 100%" />
        </template>
      </el-table-column>
      <el-table-column prop="subtotal" label="合计" />
      <el-table-column label="操作" width="150px">
        <template slot-scope="scope">
          <el-button @click="editConfirm(scope.row)">确认函</el-button>
          <el-button @click="removeItem(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <flexbox class="handle-footer">
      <div class="discount-title">整单折扣（%）：</div>
      <el-input style="width: 80px" v-model="discount_rate" @blur="discount_rate || (discount_rate = 0)"
        @input="rateChange" placeholder="请输入"></el-input>
      <div class="total-info">
        已选中产品： <span class="info-yellow">{{ productList.length }}</span>&nbsp;种&nbsp;&nbsp;总金额：
        <el-input style="width: 80px" v-model="total_price" @input="totalPriceChange"
          @blur="total_price || (total_price = 0)" placeholder="请输入"></el-input>&nbsp;元
      </div>
    </flexbox>
    <el-dialog title="确认函" :visible="confirmShow" :show-close="false" append-to-body>
      <flexbox :gutter="0" wrap="wrap">
        <flexbox-item v-for="(item, index) in confirmData" :key="index" :span="item.types == 4 ? 1 : 0.5"
          class="b-cell">
          <Confirm-form :value="item" @change="changeField" />
        </flexbox-item>
      </flexbox>
      <div slot="footer">
        <el-button @click="confirmShow = false">取 消</el-button>
        <el-button type="primary" @click="confirmSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script type="text/javascript">
  import objMixin from "./objMixin";
  import CrmRelative from "@/components/CreateCom/CrmRelative";
  import ConfirmForm from "@/components/CreateCom/ConfirmForm";
  import {
    crmDataField
  } from "@/api/customermanagement/confirmation";

  export default {
    name: "xh-product", // 关联产品
    components: {
      CrmRelative,
      ConfirmForm,
    },
    mixins: [objMixin],
    computed: {},
    watch: {
      dataValue(value) {
        this.refreshProductList();
      },
    },
    data() {
      return {
        showPopover: false, // 展示产品框
        showSelectView: false, // 内容
        productList: [],
        contractId: "", // 订单ID
        confirmShow: false, // 确认函弹窗
        productId: "", // 产品ID
        confirmData: [], // 确认函
        total_price: 0,
        discount_rate: 0,
      };
    },
    props: {
      value: {
        type: Object,
        default: () => {
          return {};
        },
      },
    },
    watch: {
      confirmShow(v) {
        if (!v) {
          this.productId = "";
          this.confirmData = [];
        }
      },
    },
    mounted() {
      this.refreshProductList();
    },
    methods: {
      /**
       * 刷新数据
       */
      refreshProductList() {
        this.productList = this.dataValue.product;
        if (this.productList.length > 0) {
          this.contractId = this.productList[0].contract_id;
        }
        this.total_price = this.dataValue.total_price;
        this.discount_rate = this.dataValue.discount_rate;
      },
      /** 选中 */
      selectInfos(data) {
        data.data.forEach((element) => {
          let obj = this.productList.find((item) => {
            return item.product_id == element.product_id;
          });
          if (!obj) {
            this.productList.push(this.getShowItem(element));
          }
        });
      },
      getShowItem(data) {
        let item = {};
        item.name = data.name;
        item.category_id_info = data.category_id_info;
        item.unit = data.unit;
        item.price = data.price;
        item.sales_price = data.price;
        item.num = 0;
        item.discount = 0;
        item.subtotal = 0;
        item.product_id = data.product_id;
        return item;
      },
      // 编辑确认函
      editConfirm(row) {
        this.productId = row.product_id;
        if (row.fieldList) {
          this.confirmData = row.fieldList;
          this.confirmShow = true;
        } else {
          crmDataField({
            product_id: row.product_id,
            contract_id: this.contractId,
          }).then((res) => {
            if (res.code == 200) {
              this.productList.forEach((i) => {
                if (i.product_id == row.product_id) {
                  i.fieldList = res.data.category;
                  this.confirmData = i.fieldList;
                  this.confirmShow = true;
                }
              });
            }
          });
        }
      },
      // 保存确认函
      confirmSubmit() {
        let list = this.confirmData.filter((i) => i.is_must == 1);
        let pass = true;
        for (const i in list) {
          const item = list[i];
          if (item.is_must == 1 && !("value" in item)) {
            this.$message.warning(`${item.title}为必填项`);
            pass = false;
            break;
          } else {
            if (item.value == "" || item.value.length == 0) {
              this.$message.warning(`${item.title}为必填项`);
              pass = false;
              break;
            }
          }
        }
        if (!pass) return;
        let result = this.confirmData.map((i) => {
          return {
            contract_confirmation_id: i.contract_confirmation_id,
            confirmation_id: i.confirmation_id,
            confirmation_category_id: i.confirmation_category_id,
            is_must: i.is_must,
            name: i.title,
            value_data: i.value || "",
            type: i.types,
            product_id: this.productId,
          };
        });
        let index = this.productList.findIndex((item) => {
          return item.product_id == this.productId;
        });
        this.productList[index]["confirmation"] = result;
        this.confirmShow = false;
        console.log(this.productList);
      },
      // 改变字段信息
      changeField(val) {
        let index = this.confirmData.findIndex(
          (i) => i.confirmation_category_id == val.confirmation_category_id
        );
        this.confirmData[index] = val;
      },
      // 单价
      salesPriceChange(data) {
        this.verifyNumberValue(data, "sales_price");
        let item = data.row;

        let discount = ((item.price - (item.sales_price || 0)) / item.price) * 100.0;
        discount = discount.toFixed(2);
        if (item.discount !== discount) {
          item.discount = discount;
        }
        this.calculateSubTotal(item);
        this.calculateToal();
      },
      // 数量
      numChange(data) {
        this.verifyNumberValue(data, "num");
        let item = data.row;
        this.calculateSubTotal(item);
        this.calculateToal();
      },
      // 折扣
      discountChange(data) {
        this.verifyNumberValue(data, "discount");
        let item = data.row;
        let sales_price = (item.price * (100.0 - parseFloat(item.discount || 0))) / 100.0;
        sales_price = sales_price.toFixed(2);
        if (item.sales_price !== sales_price) {
          item.sales_price = sales_price;
        }
        this.calculateSubTotal(item);
        this.calculateToal();
      },
      // 计算单价
      calculateSubTotal(item) {
        item.subtotal = (item.sales_price * parseFloat(item.num || 0)).toFixed(2);
      },
      // 计算总价
      calculateToal() {
        let totalPrice = this.getProductTotal();
        totalPrice = (totalPrice * (100.0 - parseFloat(this.discount_rate || 0))) / 100.0;
        this.total_price = totalPrice.toFixed(2);
        this.updateValue(); // 传递数据给父组件
      },
      /**
       * 获取产品总价(未折扣)
       */
      getProductTotal() {
        let totalPrice = 0.0;
        for (let i = 0; i < this.productList.length; i++) {
          let item = this.productList[i];
          totalPrice += parseFloat(item.subtotal);
        }
        return totalPrice;
      },
      // 总折扣
      rateChange() {
        if (/^\d+\.?\d{0,2}$/.test(this.discount_rate)) {
          this.discount_rate = this.discount_rate;
        } else {
          this.discount_rate = this.discount_rate.substring(
            0,
            this.discount_rate.length - 1
          );
        }
        this.calculateToal();
      },
      /**
       * 总价更改 折扣更改
       */
      totalPriceChange() {
        if (/^\d+\.?\d{0,2}$/.test(this.total_price)) {
          this.total_price = this.total_price;
        } else {
          this.total_price = this.total_price.substring(0, this.total_price.length - 1);
        }
        let totalPrice = this.getProductTotal();
        this.discount_rate = (
          100.0 -
          (parseFloat(this.total_price) / totalPrice) * 100
        ).toFixed(2);
        this.updateValue();
      },
      // 删除操作
      removeItem(index) {
        this.productList.splice(index, 1);
        this.calculateToal();
      },
      updateValue() {
        this.valueChange({
          product: this.productList,
          total_price: this.total_price,
          discount_rate: this.discount_rate,
        });
      },
      /**
       * 验证数据数值是否符合
       */
      verifyNumberValue(data, field) {
        if (/^\d+\.?\d{0,2}$/.test(data.row[field])) {
          data.row[field] = data.row[field];
        } else {
          data.row[field] = data.row[field].substring(0, data.row[field].length - 1);
        }
      },
    },
  };

</script>
<style lang="scss" scoped>
  .handel-header {
    button {
      float: right;
      margin-bottom: 10px;
    }
  }

  .el-table /deep/ thead th {
    font-size: 12px;
  }

  .el-table /deep/ tbody tr td {
    font-size: 12px;
  }

  .handle-footer {
    position: relative;
    font-size: 12px;
    padding: 5px;

    .discount-title {
      color: #666;
    }

    .total-info {
      position: absolute;
      right: 20px;
      top: 5px;

      .info-yellow {
        color: #fd715a;
      }
    }
  }

  .flex-box {
    display: flex;
    flex-wrap: wrap;

    >div:nth-child(2n - 1) {
      width: calc(50% - 10px);
      margin-right: 20px;
    }

    >div:nth-child(2n) {
      width: calc(50% - 10px);
    }
  }

</style>
